import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:rxdart/rxdart.dart';
import 'package:redux/redux.dart';
import 'package:wuxu_flutter_lianxi/dao/UserDao.dart';
import 'package:wuxu_flutter_lianxi/model/user.dart';
import 'package:wuxu_flutter_lianxi/redux/middleware/epic_store.dart';
import 'package:wuxu_flutter_lianxi/redux/wx_state.dart';

import '../route/navigator_util.dart';

///
/// 登录 Redux
///
///

final LoginReducer = combineReducers<UserInfo?>([
  TypedReducer<UserInfo?,LoginSuccessAction>(_loginResult),
]);

UserInfo? _loginResult(UserInfo? result,LoginSuccessAction action){
  if(action.user!=null){
    NavigatorUtil.goMain(action.context);
    return action.user;
  }else{
    Fluttertoast.showToast(msg: "账号或密码错误");
    return result;
  }
}

class LoginAction{
  final BuildContext context;//用于跳转页面
  final String username;
  final String password;

  LoginAction(this.context, this.username, this.password);
}

class LoginSuccessAction{
  final BuildContext context;
  final UserInfo? user;

  LoginSuccessAction(this.context,this.user);
}

class LoginOutAction{
  final BuildContext context;

  LoginOutAction(this.context);
}

Stream<dynamic> epicLogin(Stream<dynamic> actions,EpicStore<WXState> store){
  Stream<dynamic> loginIn(LoginAction action,EpicStore<WXState> store) async*{
    var res = await UserDao.login(action.username, action.password,store);
    yield LoginSuccessAction(action.context,res?.data??null);
  }

  var newStream = actions.whereType<LoginAction>().switchMap((value) => loginIn(value,store));

  newStream.listen((event) {
      print("newStream listen ${event.toString()}");
  });
  return newStream;
     
}


///
/// 中间件
///
class LoginMiddleware implements MiddlewareClass<WXState>{
  @override
  call(Store<WXState> store, action, NextDispatcher next) {

    if (action is LoginOutAction){
      //退出登录操作
      UserDao.clearUserInfo();
      //跳转到登录
      NavigatorUtil.goLogin(action.context);
    }else if (action is LoginSuccessAction){
      //这里处理是没有效果的，因为都是中间件，这里是同步的，比异步中间件会先执行，所以需要将结果放在reducer函数中
    }

    next(action);
  }
}